<script lang="ts" setup>
import {
  ElButton,
  ElTabs,
  ElTabPane,
  ElRow,
  ElCol,
  ElIcon,
  ElMessage,
  ElImage,
  ElMessageBox,
} from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { router } from "#/router";
import { getAirportById } from "#/api/sys/equipment";
import GaoAmap from "./selectMap.vue";

const activeName = ref("first");
const record = reactive({
  organizationName: "",
  airportName: "",
  longitude: "", // 经度
  latitude: "", // 纬度
  gatewaySn: "",
  description: "",
  airportImage: "",
  ipAddress: "",
  gateway: "",
  videoAddress: "",
  windSpeedThreshold: "",
  rainfallThreshold: "",
  droneIds: [],
  droneList: [],
  // 运行信息
  status: "",
  totalTaskCount: "",
  totalTaskTime: "",
  totalTaskDistance: "",
  airportMaintenanceInfo: {
    firmwareUpgradeStatus: "",
    firmwareVersion: "",
    lastMaintainTime: "",
    lastMaintainType: "",
    modeCode: "",
    alarmState: "",
  },
});
const srcList = ref([]);
const disabled = ref(true);

const handleBack = () => {
  router.go(-1);
};

// 地图
const amapVisible = ref(false);
const mapConfig = reactive({
  defaultAddress: "",
  defaultPoint: [],
});

const lookLocation = () => {
  if (record.longitude && record.latitude) {
    mapConfig.defaultPoint = [record.longitude, record.latitude];
    mapConfig.defaultAddress = record.address;
    amapVisible.value = true;
  } else {
    ElMessage.warning("位置信息不完整");
  }
};

const getPosition = (infoObj) => {
  amapVisible.value = false;
};

const getDetail = async () => {
  try {
    const params = {
      id: router.currentRoute.value.query.id,
    };
    const response = await getAirportById(params);

    // 检查接口返回状态码
    if (response.code !== 200) {
      ElMessage.error(response.msg || "获取机场详情失败");
      // 设置默认值
      setDefaultValues();
      return;
    }

    const data = response.data;

    // 成功获取数据，更新record对象
    record.organizationName = data.organizationName || "--";
    record.airportName = data.airportName || "--";
    record.longitude = data.longitude || "--"; // 经度
    record.latitude = data.latitude || "--"; // 纬度
    record.address = data.address || "--";
    record.gatewaySn = data.gatewaySn || "--";
    record.description = data.description || "--";
    record.airportImage = data.imageUrl || "";
    srcList.value = [data.imageUrl || ""];
    record.ipAddress = data.ipAddress || "--";
    record.gateway = data.gateway || "--";
    record.videoAddress = data.videoAddress || "--";
    record.windSpeedThreshold =
      data.windSpeedThreshold !== undefined ? data.windSpeedThreshold : "--";
    record.rainfallThreshold =
      data.rainfallThreshold !== undefined ? data.rainfallThreshold : "--";
    record.droneIds = data.droneIds || [];
    record.droneList = data.droneList || [];
    record.status = data.status || "--";
    record.totalTaskCount =
      data.totalTaskCount !== undefined ? data.totalTaskCount : "--";
    record.totalTaskTime =
      data.totalTaskTime !== undefined ? data.totalTaskTime : "--";
    record.totalTaskDistance =
      data.totalTaskDistance !== undefined ? data.totalTaskDistance : "--";

    mapConfig.defaultPoint =
      data.longitude && data.latitude ? [data.longitude, data.latitude] : [];
    mapConfig.defaultAddress = data.address || "";
    disabled.value = false;
    
    // 处理 airportMaintenanceInfo，确保它不会是 null
    record.airportMaintenanceInfo = data.airportMaintenanceInfo || {
      lastMaintainTime: "--",
      modeCode: "--",
      firmwareVersion: "--",
      lastMaintainType: "--",
      firmwareUpgradeStatus: "--",
      alarmState: "--"
    };
  } catch (error) {
    console.error("获取机场详情异常:", error);
    ElMessage.error("获取机场详情异常: " + (error.message || "未知错误"));
    // 设置默认值
    setDefaultValues();
  }
};

// 设置默认值的函数
const setDefaultValues = () => {
  record.organizationName = "--";
  record.airportName = "--";
  record.longitude = "--"; // 经度
  record.latitude = "--"; // 纬度
  record.address = "--";
  record.gatewaySn = "--";
  record.description = "--";
  record.airportImage = "";
  srcList.value = [""];
  record.ipAddress = "--";
  record.gateway = "--";
  record.videoAddress = "--";
  record.windSpeedThreshold = "--";
  record.rainfallThreshold = "--";
  record.droneIds = [];
  record.droneList = [];
  record.status = "--";
  record.totalTaskCount = "--";
  record.totalTaskTime = "--";
  record.totalTaskDistance = "--";

  // 设置 airportMaintenanceInfo 的默认值，与 getDetail 中保持一致
  record.airportMaintenanceInfo = {
    lastMaintainTime: "--",
    modeCode: "--",
    firmwareVersion: "--",
    lastMaintainType: "--",
    firmwareUpgradeStatus: "--",
    alarmState: "--"
  };

  mapConfig.defaultPoint = [];
  mapConfig.defaultAddress = "";
  disabled.value = true;
};

const handleUpgrade = async (item) => {
  try {
    await ElMessageBox.confirm(
      `是否升级固件版本至【${item.firmwareVersion}】吗？`,
      "提示",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true, // 启用HTML内容渲染
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              // await deleteDrone(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("操作成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
      console.error("操作无人机失败:", error);
    }
  }
};

const Upgrading = async () => {
  try {
    await ElMessageBox.confirm(`升级中`, {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
      console.error("操作无人机失败:", error);
    }
  }
};

onMounted(() => {
  getDetail();
});
</script>

<template>
  <div class="detailPage mg-10 pd-20">
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName" class="demo-tabs">
      <ElTabPane label="机场详情" name="first">
        <div class="page">
          <h3 class="title">归属</h3>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">所属组织：</span>
                  <span>{{ record.organizationName }}</span>
                </p>
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">机场信息</h3>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场名称：</span>
                  <span class="bold">{{ record.airportName }}</span>
                </p>
              </div>
            </ElCol>

            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">IP地址：</span>
                  <span class="bold">{{ record.ipAddress }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">SN码：</span>
                  <span class="bold">{{ record.gatewaySn }}</span>
                </p>
              </div>
            </ElCol>
            <!-- <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">网关：</span>
                  <span class="bold">{{ record.gateway }}</span>
                </p>
              </div>
            </ElCol> 
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">风速阈值：</span>
                  <span class="bold">{{ record.windSpeedThreshold }}m/s</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">降雨阈值：</span>
                  <span class="bold">{{ record.rainfallThreshold }}mm</span>
                </p>
              </div>
            </ElCol>-->
          </ElRow>
          <ElRow>
            <!-- <ElCol
              :xs="24"
              :sm="12"
              :md="12"
              :lg="12"
              :xl="12"
              class="searchCol"
            >
              <div>
                <p class="pText">
                  <span class="labelText">视频地址：</span>
                  <span class="bold">{{ record.videoAddress }}</span>
                </p>
              </div>
            </ElCol> -->
            <ElCol
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="searchCol"
            >
              <div>
                <p class="pText">
                  <span class="labelText">机场位置：</span>
                  <!-- （{{ record.longitude }},{{ record.latitude }}） -->
                  <span class="bold">{{ record.address }}</span>
                  <ElButton
                    link
                    type="primary"
                    size="small"
                    @click="lookLocation"
                    :disabled="disabled"
                    style="padding: 0; margin-left: 8px; font-size: 14px"
                  >
                    <ElIcon><Location /></ElIcon>
                    查看位置
                  </ElButton>
                </p>
              </div>
            </ElCol>
            <!-- <ElCol :xs="24" :sm="12" :md="12" :lg="8" :xl="8" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场描述：</span>
                  <span class="bold">{{ record.description }}</span>
                </p>
              </div>
            </ElCol> -->
          </ElRow>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div style="display: flex">
                <p class="pText">
                  <span class="labelText">机场图片：</span>
                </p>
                <ElImage
                  style="width: 60px; height: 60px"
                  :src="record.airportImage"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="srcList"
                  show-progress
                  :initial-index="4"
                  fit="cover"
                />
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">运行信息</h3>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场状态：</span>
                  <span style="color: #67c23a" v-if="record.status == '在线'">{{
                    record.status
                  }}</span>
                  <span style="color: #f56c6c" v-if="record.status == '离线'">{{
                    record.status
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">累计任务次数：</span>
                  <span class="bold">{{ record.totalTaskCount }}次</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">累计任务时间：</span>
                  <span class="bold">{{ record.totalTaskTime }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">累计任务距离：</span>
                  <span class="bold">{{ record.totalTaskDistance }}米</span>
                </p>
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">保养信息</h3>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">上次保养时间：</span>
                  <span class="bold">{{
                    record.airportMaintenanceInfo.lastMaintainTime
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场任务状态：</span>
                  <!-- "0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中","5":"待标定" -->
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 0"
                    >空闲中</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 1"
                    >现场调试</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 2"
                    >远程调试</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 3"
                    >固件升级中</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 4"
                    >作业中</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.modeCode == 5"
                    >待标定</span
                  >
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">固件版本：</span>
                  <span class="bold">{{
                    record.airportMaintenanceInfo.firmwareVersion
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">上次保养类型：</span>
                  <!-- "0":"无保养","17":"机场常规保养","18":"机场深度保养" -->
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.lastMaintainType == 0"
                    style="color: #f56c6c"
                    >无保养</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.lastMaintainType == 17"
                    >机场常规保养</span
                  >
                  <span
                    class="bold"
                    v-if="record.airportMaintenanceInfo.lastMaintainType == 18"
                    >机场深度保养</span
                  >
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">固件升级状态：</span>
                  <!-- "0":"未升级","1":"升级中" -->
                  <span
                    v-if="
                      record.airportMaintenanceInfo.firmwareUpgradeStatus == 0
                    "
                    class="bold firmware-status"
                    style="color: #f56c6c; cursor: pointer"
                    @click="handleUpgrade(record)"
                    >可升级<i class="triangle-up"> </i
                  ></span>
                  <span
                    v-if="
                      record.airportMaintenanceInfo.firmwareUpgradeStatus == 1
                    "
                    class="bold"
                    style="color: var(--el-color-primary); cursor: pointer"
                    @click="Upgrading(record)"
                    >升级中<i class="triangle-up blue"> </i
                  ></span>
                  <!-- <span
                    class="bold"
                    style="color: #67c23a; cursor: pointer"
                    v-if="record.airportMaintenanceInfo.firmwareUpgradeStatus == 3"
                    >最新版本<i class="triangle-up green"></i
                  ></span> -->
                </p>
              </div>
            </ElCol>
            <!-- <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">下次保养剩余天数：</span>                  
                  <span class="bold">{{record.maintenanceTimeLeft}}天</span>
                </p>
              </div>
            </ElCol> -->
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场声光报警状态：</span>
                  <!-- 0 未开启 1已开启 -->
                  <span class="bold">{{
                    record.airportMaintenanceInfo.alarmState == 1
                      ? "已开启"
                      : "未开启"
                  }}</span>
                </p>
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">关联无人机（{{ record.droneList.length }}）</h3>
          <ElRow>
            <ElCol
              :span="24"
              class="searchCol droneList"
              v-if="record.droneList.length > 0"
            >
              <div
                class="airportList"
                v-for="item in record.droneList"
                :key="item.id"
              >
                <ul>
                  <li class="name" :title="item.droneName">
                    {{ item.droneName }}
                  </li>
                  <li>
                    品牌：
                    <span>{{ item.droneBrand }}</span>
                  </li>
                  <li>
                    型号：
                    <span>{{ item.droneModel }}</span>
                  </li>
                  <li>
                    状态：
                    <span
                      v-if="item.status == '作业中'"
                      style="color: #67c23a"
                      >{{ item.status }}</span
                    >
                    <span v-if="item.status == '离线'" style="color: #f56c6c">{{
                      item.status
                    }}</span>
                    <span v-if="item.status == '待命'" style="color: #e6a23c">{{
                      item.status
                    }}</span>
                  </li>
                  <li>
                    累计任务次数：
                    <span>{{ item.taskCount }}次</span>
                  </li>
                  <li>
                    累计任务距离：
                    <span>{{ item.totalTaskDistance }}米</span>
                  </li>
                </ul>
              </div>
            </ElCol>
            <ElCol :span="24" class="searchCol droneList" v-else>
              <p class="pText labelText">暂无关联无人机</p>
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>
    </ElTabs>
    <GaoAmap
      :isShow="amapVisible"
      :data="mapConfig"
      :showSearch="false"
      @getPosition="getPosition"
    ></GaoAmap>
  </div>
</template>
<style scoped>
h3 {
  font-weight: 900;
  color: #303133;
}

.title {
  padding: 8px 10px;
  margin-bottom: 16px;
  font-size: 14px;
  background: #f5f7fa;
}

.bold {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

/* 机场描述文本样式 */
.description-text {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
  line-height: 1.5;
  /* max-width: calc(100% - 100px); */
}

.pText {
  font-size: 14px;
  text-indent: 10px;
}

.labelText {
  font-size: 14px;
  color: #909399;
}

img {
  height: 100px;
}

.searchCol {
  display: flex;
}

.droneList {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  width: 100%;
}

.airportList {
  width: 224px;
  padding-bottom: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

ul {
  float: left;
  width: 224px;
}

ul li {
  padding-left: 16px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #909399;
  text-align: left;
  width: 224px;
}

li:last-child {
  margin-bottom: 0;
}

.name {
  height: 44px;
  padding: 0 6px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  line-height: 44px;
  color: #303133;
  text-align: center;
  background: #f5f7fa;
  border-radius: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status {
  color: #67c23a;
}

li span {
  color: #303133;
}

.el-col {
  margin-bottom: 20px;
}

.firmware-status {
  position: relative;
}

.triangle-up {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 0px;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 16px solid #f56c6c;
  vertical-align: middle;
}

.blue {
  border-bottom: 16px solid var(--el-color-primary);
}

.green {
  border-bottom: 16px solid #67c23a;
}
</style>